#include "SendDataWorker.h"

#include <QElapsedTimer>
#include <QFile>
#include <QTextStream>
#include <QThread>

SendDataWorker::SendDataWorker(QObject *parent)
    : QObject(parent), m_run(false), m_numLoops(0) {}

void SendDataWorker::stop() { m_run = false; }

void SendDataWorker::start() {
  QFile file(m_filePath);
  if (!file.open(QIODevice::ReadOnly)) {
    emit finished();
    return;
  }

  m_run = true;

  QVector<QPair<QString, int>> data; // 用于存储数据和延时

  QTextStream in(&file);
  in.readLine(); // Skip header line

  // 读取数据到内存
  while (!in.atEnd()) {
    QString line = in.readLine();
    QStringList items = line.split(",");
    if (items.size() >= 3) {
      int delay = items.at(2).toInt(); // 假设延时在第三列
      data.append(qMakePair(line, delay));
    }
  }
  file.close();

  // 遍历数据并发送
  QElapsedTimer timer;
  for (int i = 0; ((i < m_numLoops) || (m_numLoops == 0)) && m_run; ++i) {
    for (const auto &item : qAsConst(data)) {
      if (m_run) {
        emit sigSendRow(item.first); // 发送数据
        int delay = item.second;

        // 精确延时
        timer.start();
        while (timer.elapsed() < delay) {
          QThread::yieldCurrentThread(); // 减少CPU使用
        }
      } else {
        break;
      }
    }
  }
  emit finished();
  m_run = false;
}

void SendDataWorker::setNumLoops(int numLoops) { m_numLoops = numLoops; }

void SendDataWorker::setFilePath(const QString &filePath) {
  m_filePath = filePath;
}
